
import {
  $tokenName,
  $getToken,
  $setToken,
  $formatSearchParam,
  $version
} from '@/plugins/baseInfo'
const querystring = require("querystring");
export const createCommonSingleton = function (fn) { // 通用 的 惰性单例
  if (typeof fn !== 'function') throw new Error('必须传入一个生成单例的函数')
  let div = null
  return function () {
    return div || (div = fn.apply(this, arguments))
  }
}

export const getFileType = (fileType) => {
  const video = [
    'DRC',
    'DSM',
    'DSV',
    'DSA',
    'DSS',
    'VOB',
    'IFO',
    'D2V',
    'FLV',
    'FLI',
    'FLC',
    'FLIC',
    'IVF',
    'MKV',
    'MPG',
    'MPEG',
    'MPE',
    'M1V',
    'M2V',
    'MPV2',
    'MP2V',
    'DAT',
    'TS',
    'TP',
    'TPR',
    'PVA',
    'PSS',
    'MP4',
    'M4V',
    'M4P',
    'M4B',
    '3GP',
    '3GPP',
    '3G2',
    '3GP2',
    'OGM',
    'MOV',
    'QT',
    'AMR',
    'RATDVD',
    'RT',
    'RP',
    'SMI',
    'SMIL',
    'RM',
    'RAM',
    'RMVB',
    'RPM',
    'ROQ',
    'SWF',
    'SMK',
    'BIK',
    'WMV',
    'WMP',
    'WM',
    'ASF',
    'AVI',
    'ASX',
    'M3U',
    'PLS',
    'WVX',
    'WAX',
    'WMX',
    'MPCPL'
  ]
  const images = [
    'BMP',
    'JPG',
    'JPEG',
    'PNG',
    'TIF',
    'GIF',
    'PCX',
    'TGA',
    'EXIF',
    'FPX',
    'SVG',
    'PSD',
    'CDR',
    'PCD',
    'DXF',
    'UFO',
    'EPS',
    'AI',
    'RAW',
    'WMF',
    'WEBP'
  ]
  const excel = ['XLS', 'XLSM', 'XLSX', 'XLTX', 'XLTM', 'XLSB']
  const doc = ['DOC', 'DOCX']
  fileType = fileType.toUpperCase()
  if (video.indexOf(fileType) >= 0) return 'video'
  if (images.indexOf(fileType) >= 0) return 'img'
  if (excel.indexOf(fileType) >= 0) return 'xls'
  if (doc.indexOf(fileType) >= 0) return 'doc'
  if (fileType === 'DWG') return 'dwg'
  if (fileType === 'PDF' || fileType === 'pdf') return 'pdf'
  return 'other'
}

export const loadJs = (src) => {
  return new Promise((resolve) => {
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.async = false
    script.src = src
    document.getElementsByTagName('head')[0].appendChild(script)
    script.onload = function () {
      resolve()
    }
  })
}

export const loadCss = (href) => {
  const node = document.createElement('link')
  node.rel = 'stylesheet'
  node.href = href
  document.getElementsByTagName('head')[0].appendChild(node)
}

export const getStreamViewUrl = (url, fileType, mood, params) => {
  if (!url) return ''
  let resContentType = ''
  // 非结构化平台需要加参数
  if (mood === 'unstructured') {
    const types = {
      pdf: 'responseContentType=application/pdf',
      img: 'responseContentType=image/*',
      video: 'responseContentType=video/*'
    }
    resContentType = types[fileType]
  }
  // OSS存储
  if (mood === 'OSS' && fileType === 'pdf') {
    resContentType = 'response-content-type=application/pdf'
  }
  // 当Url不存在需要添加的头信息时，追加该头信息
  if (resContentType && url.indexOf(resContentType) === -1) {
    url += `${url.indexOf('?') === -1 ? '?' : '&'}${resContentType}`
  }
  if (params !== null && typeof(params) === 'object') {
    // 1 预览，2 下载；不传默认为下载,如果默认没有传type设置type为1
    // 特殊情况：为服务中excel预览时传1会转换成PDF，xslx格式可以支持前端预览，需要特殊处理
    !params.type && (params.type = '1')
    Object.keys(params).forEach((key) => {
      let value = params[key]
      // 当文件类型为xls时，需要强制转换成PDF后缀，由文件附件转换成pdf进行预览
      if (key === 'filename' && ~value.indexOf('xls')) {
        value = value.replace(/xls$/g, 'pdf').replace(/\[/g, '').replace(/\]/g, '')
      }
      url += `${url.indexOf('?') === -1 ? '?' : '&'}${key}=${value}`
    })
  }
  // return replaceUrl(url)
  return url
}

/**
 * 替换url        --  这个是 别人 写了这玩意儿 复制过来先 反正不知道用在什么场景
 * @param {String} url      
 */
const replaceUrl = (url) => {
  const ipRplaceMap = (window.globalConfig && window.globalConfig.ipRplaceMap) || {}
  for (const key in ipRplaceMap) {
    if (new RegExp(key).test(url)) {
      url = url.replace(new RegExp(key), ipRplaceMap[key])
      break
    }
  }
  return url
}

export const downloadFile = (url, fileName) => {

  const param = {
    Authorization: $getToken(),
    contentType: 'application/octet-stream',
    filename: fileName
  }
  
  const aLink = document.createElement('a')
  aLink.style.display = 'none'

  url = url + '?' + querystring.stringify(param)
  
  aLink.href = url.replace(/[\[|\]|，|\,|#]/g, '')
  document.body.appendChild(aLink)
  aLink.setAttribute('download', fileName)
  aLink.click()
  document.body.removeChild(aLink)
}